<template>
	<view class="rootview">
		<form @submit="addSave">
			<view class="">
				<text>姓名：</text>
			</view>
			<view>
				<input type="text" name="name" placeholder="请输入姓名" />
			</view>
			<view class="">
				<text>电话：</text>
			</view>
			<view>
				<input type="text" name="tel" placeholder="请输入电话" />
			</view>
			<button form-type="submit">保存</button>
		</form>
	</view>
</template>

<script>
	import db from '@/js_sdk/uni-clientDB/index.js';
	const dbCmd = db.command;
	export default {
		data() {
			return {};
		},
		methods: {
			addSave: function(e) {
				// console.log('submit数据：' , e.detail.value)
				var formdata = e.detail.value
				if (!formdata.name) {
					uni.showModal({
						content: '姓名不能为空',
						showCancel: false
					})
					return
				}
				if (!/^\+?[0-9-]{3,20}$/.test(formdata.tel)) {
					uni.showModal({
						content: '电话号码不合法',
						showCancel: false
					})
					return
				}
				uniCloud.callFunction({
					name: 'uni-clientDB',
					data: {
						command: db.collection('phonebook').add(formdata)
					},
					success(res) {
						// console.log(res);
						console.log("newid: ", res.result.id);
						//redirect方式跳转到新建好的详情页面
						uni.redirectTo({
							url: "../detail/detail?id=" + res.result.id
						})
						uni.$emit('reloadList')
					},
					fail(err) {
						console.error(err);
						uni.showModal({
							content: err.message || '服务器连接失败',
							showCancel: false
						});
					}
				});
			}
		}
	};
</script>

<style>
	.rootview {
		padding: 15px;
	}
</style>
